//
//  SNBpAndOxView.m
//  project
//
//  Created by 黄建华 on 2018/8/22.
//  Copyright © 2018年 黄建华. All rights reserved.
//

#import "SNBpAndOxView.h"

@implementation SNBpAndOxView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self createView];
    }
    return self;
}

- (void)createView
{
    UIImageView *imageV = [[UIImageView alloc] init];
    imageV.frame = SNFRAME(10, 10, 50, 50);
    imageV.image = [UIImage image:@"F血压血氧"];
    [self addSubview:imageV];
    
    UILabel *type = [[UILabel alloc] init];
    type.textColor = [UIColor blackColor];
    type.frame     = SNFRAME(imageV.right + 10, imageV.top + 7, 100, 20);
    type.font      = SNFONT(16.0);
    type.text      = SN_Text(@"血压血氧");
    [self addSubview:type];
    
    UILabel *dateLabel = [[UILabel alloc] init];
    dateLabel.textColor = SNCOLORGRAYLINE;
    dateLabel.frame     = SNFRAME(imageV.right + 10, type.bottom, 100, 20);
    dateLabel.font      = SNFONT(13.0);
    dateLabel.text = [[NSDate date]dateMonthAndDay];
    [self addSubview:dateLabel];

    NSArray *array = @[UIColorHEX(0xf96c9c),UIColorHEX(0x67cefc), UIColorHEX(0xf9269b)];
    NSArray *titleArr = @[SN_Text(@"收缩压"),SN_Text(@"舒张压"),SN_Text(@"血氧")];
    for (int i = 0; i <3; i ++) {
        UIView *view = [[UIView alloc] init];
        view.frame = SNFRAME(screenWidth/2 + 20 + (screenWidth/6)*i, 15, 15, 15);
        view.backgroundColor = [array objectAtIndex:i];
        [self addSubview:view];
        
        UILabel *label = [[UILabel alloc] init];
        label.textColor = [UIColor blackColor];
        label.font = SNFONTMIN(10.0);
        label.frame = SNFRAME(view.centerX - 30, view.bottom +10, 60, 20);
        label.textAlignment = NSTextAlignmentCenter;
        label.text = [titleArr objectAtIndex:i];
        label.adjustsFontSizeToFitWidth = YES;
        label.minimumScaleFactor = 0.5;
        [self addSubview:label];
    }
    
    self.lineChart = [[LFLineChart alloc] initWithFrame:CGRectMake(0,imageV.bottom - 20, screenWidth,self.height - imageV.bottom +20 - 60)];
    self.lineChart.backgroundColor = [UIColor clearColor];
    [self addSubview:_lineChart];
    self.lineChart.title = @""; // 折线图名称
    
    NSMutableArray *orderedArray = [[NSMutableArray alloc]init];
    float max = 0;
    for(int i = 0; i < 24 *2; i++){
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        NSString *xValue;
        NSString *yValue;
        
        if (i %8 == 0) {
            xValue = [NSString stringWithFormat:@"%d",i/2];
        }
        else
        {
            xValue = @"";
        }
        
        yValue = [NSString stringWithFormat:@"%u",0];
        dict = [@{
                  @"Xvalue" : xValue, @"value":yValue
                  } mutableCopy];
        
        [orderedArray addObject:dict];
    }
    NSDictionary *dict = @{@"Xvalue" : @"24", @"value":@""};
    [orderedArray addObject:dict];
    
    max = 10;
    self.lineChart.maxValue = max;
    // 24 *2   280/48
    float width =(screenWidth - 40 -40)/48.0;
    self.lineChart.xScaleMarkLEN = width;
    self.lineChart.yMarkTitles = @[@"",@"50",@"100",@"150",@"200"];
    
    [self.lineChart setXMarkTitlesAndValues:orderedArray titleKey:@"Xvalue" valueKey:@"value" withOtherArray:nil withColor:UIColorHEX(0xf9269b)]; // X轴刻度标签及相应的值
    
    //设置完数据等属性后绘图折线图
    [self.lineChart mapping];
    
    _showLabel1 = [[UILabel alloc] init];
    _showLabel1.textColor = [UIColor blackColor];
    _showLabel1.textAlignment = NSTextAlignmentCenter;
    _showLabel1.frame = SNFRAME(0, self.lineChart.bottom + 8 , screenWidth/3.0, 20);
    _showLabel1.font = SNFONT(18.0);
    _showLabel1.text = [NSString stringWithFormat:@"0 mmHg"];
    [self addSubview: _showLabel1];
    
    _showLabel2 = [[UILabel alloc] init];
    _showLabel2.textColor = [UIColor blackColor];
    _showLabel2.textAlignment = NSTextAlignmentCenter;
    _showLabel2.frame = SNFRAME(screenWidth/3.0, self.lineChart.bottom + 8 , screenWidth/3.0, 20);
    _showLabel2.font = SNFONT(18.0);
    _showLabel2.text = [NSString stringWithFormat:@"0 mmHg"];
    [self addSubview: _showLabel2];
    
    _showLabel3 = [[UILabel alloc] init];
    _showLabel3.textColor = [UIColor blackColor];
    _showLabel3.textAlignment = NSTextAlignmentCenter;
    _showLabel3.frame = SNFRAME(screenWidth/3.0 *2, self.lineChart.bottom + 8 , screenWidth/3.0, 20);
    _showLabel3.font = SNFONT(18.0);
    _showLabel3.text = [NSString stringWithFormat:@"0 %%"];
    [self addSubview: _showLabel3];
    
    NSArray *titleArray = [NSArray arrayWithObjects:SN_Text(@"平均舒张压"),SN_Text(@"平均收缩压"),SN_Text(@"平均血氧值"), nil];
    for (int k = 0; k <3; k++) {
        UILabel *label = [[UILabel alloc] init];
        label.textColor = UIColorHEX(0x717273);
        label.textAlignment = NSTextAlignmentCenter;
        label.frame = SNFRAME(k *screenWidth/3.0, _showLabel1.bottom + 7 , screenWidth/3.0, 20);
        label.font = SNFONT(15.0);
        label.text = [titleArray objectAtIndex:k];
        label.adjustsFontSizeToFitWidth = YES;
        label.minimumScaleFactor = 0.6;
        [self addSubview:label];
    }
    [self updateValueLabel];
    type.adjustsFontSizeToFitWidth = YES;
    type.minimumScaleFactor = 0.6;
}

- (void)updateValueLabel
{
    [_showLabel1 setAttributedText:[SN_PublicClass label1With:_showLabel1.text withFontsize:13.0 withChangeText1:@"mmHg" withChangeText2:@"mmHg"]];
    [_showLabel2 setAttributedText:[SN_PublicClass label1With:_showLabel2.text withFontsize:13.0 withChangeText1:@"mmHg" withChangeText2:@"mmHg"]];
}

// 血氧
- (NSArray *)getOXArray:(FriendModel *)model
{
    NSArray *heartArray = model.oxHistory;
    NSString *todayDateString = [[NSDate date]dateToDayString];
    NSDictionary *dic = [NSDictionary dictionary];
    for (NSDictionary *dd in heartArray) {
        NSString *dicDateString = dd[@"datestring"];
        if ([todayDateString isEqualToString:dicDateString]) {
            dic = [NSDictionary dictionaryWithDictionary:dd];
            break;
        }
    }
    NSString *oxAve = StrByInt([dic[@"oxAve"]integerValue]);
    _showLabel3.text = [NSString stringWithFormat:@"%@ %%",oxAve];
    [self updateValueLabel];
    
    NSArray *dataArray = dic[@"oxdatas"];//所有心率
    NSMutableArray *heartValueArray48 = [NSMutableArray array];
    for (int i = 0; i < 48; i++) {
        [heartValueArray48 addObject:@"0"];
    }
    
    NSMutableArray *allModelArray = [NSMutableArray array];
    for (NSDictionary *d in dataArray) {
        NSInteger heartValue = [d[@"value"] integerValue];
        NSString *time = d[@"time"];
        
        if ([time containsString:@":"] && heartValue >=55) {
            NSArray *timeArray = [time componentsSeparatedByString:@":"];
            NSInteger mins = [[timeArray firstObject]integerValue]*60 + [[timeArray lastObject]integerValue];
            HeartSubModel *model = [[HeartSubModel alloc] init];
            model.heartValue = heartValue;
            model.count = mins /30;
            model.countMins = mins;
            [allModelArray addObject:model];
        }
    }
    
    for (int k = 0; k < heartValueArray48.count; k++) {
        int           totalValue   =0;
        int           aveValue     = 0;
        int           valueCount        = 0;
        for (int i=0; i<allModelArray.count; i++) {
            HeartSubModel *heartSubModel = [allModelArray objectAtIndex:i];
            if (heartSubModel.count==k) {
                valueCount++;
                totalValue += heartSubModel.heartValue;
            }
            if(i==allModelArray.count-1){
                if (totalValue &&valueCount) {
                    aveValue = totalValue/valueCount;
                    [heartValueArray48 replaceObjectAtIndex:k withObject:StrByInt(aveValue)];
                }
            }
        }
    }
    //    NSLog(@"心率>>>>%@",heartValueArray48);
    NSMutableArray *orderedArray = [[NSMutableArray alloc]init];
    for(int k = 0; k < heartValueArray48.count; k++){
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        NSString *xValue;
        NSString *yValue;
        
        NSInteger heartValue = [[heartValueArray48 objectAtIndex:k]integerValue];
        if (k %8 == 0) {
            xValue = [NSString stringWithFormat:@"%d",k/2];
        }
        else
        {
            xValue = @"";
        }
        if (heartValue >90) {
            heartValue = heartValue -90;
        }
        yValue = [NSString stringWithFormat:@"%ld",heartValue];
        dict = [@{
                  @"Xvalue" : xValue, @"value":yValue
                  } mutableCopy];
        
        [orderedArray addObject:dict];
    }
    NSDictionary *dict = @{@"Xvalue" : @"24", @"value":@""};
    [orderedArray addObject:dict];
    return orderedArray;
}

- (NSArray *)getBpArray:(FriendModel *)model
{
    NSArray *heartArray = model.bpHistory;
    NSString *todayDateString = [[NSDate date]dateToDayString];
    NSDictionary *dic = [NSDictionary dictionary];
    for (NSDictionary *dd in heartArray) {
        NSString *dicDateString = dd[@"datestring"];
        if ([todayDateString isEqualToString:dicDateString]) {
            dic = [NSDictionary dictionaryWithDictionary:dd];
            break;
        }
    }
    NSString *sbpAve = StrByInt([dic[@"SBPave"]integerValue]);
    NSString *dbpAve = StrByInt([dic[@"DBPave"]integerValue]);
    _showLabel1.text = [NSString stringWithFormat:@"%@ mmHg",dbpAve];
    _showLabel2.text = [NSString stringWithFormat:@"%@ mmHg",sbpAve];
    [self updateValueLabel];
    
    NSArray *dataArray = dic[@"bpdatas"];//所有血压
    NSMutableArray *sbpArray = [NSMutableArray array];
    NSMutableArray *dbpArray = [NSMutableArray array];
    for (int i = 0; i < 48; i++) {
        [sbpArray addObject:@"0"];
        [dbpArray addObject:@"0"];
    }
    
    NSMutableArray *allModelArray = [NSMutableArray array];
    for (NSDictionary *d in dataArray) {
        NSInteger sbpValue = [d[@"SBPValue"] integerValue];
        NSInteger dbpValue = [d[@"DBPValue"] integerValue];
        NSString *time = d[@"time"];
        
        if ([time containsString:@":"] && sbpValue > 0 && dbpValue >0) {
            NSArray *timeArray = [time componentsSeparatedByString:@":"];
            NSInteger mins = [[timeArray firstObject]integerValue]*60 + [[timeArray lastObject]integerValue];
            bpSubModel *model = [[bpSubModel alloc] init];
            model.SBPValue = sbpValue;
            model.DBPValue = dbpValue;
            model.count = mins /30;
            model.countMins = mins;
            [allModelArray addObject:model];
        }
    }
    
    for (int k = 0; k < sbpArray.count; k++) {
        int           totalValue   =0;
        int           aveValue     = 0;
        int           valueCount        = 0;
        for (int i=0; i<allModelArray.count; i++) {
            bpSubModel *heartSubModel = [allModelArray objectAtIndex:i];
            if (heartSubModel.count==k) {
                valueCount++;
                totalValue += heartSubModel.SBPValue;
            }
            if(i==allModelArray.count-1){
                if (totalValue &&valueCount) {
                  aveValue = totalValue/valueCount;
                }
                [sbpArray replaceObjectAtIndex:k withObject:StrByInt(aveValue)];
            }
        }
    }
    
    for (int k = 0; k < dbpArray.count; k++) {
        int           totalValue   =0;
        int           aveValue     = 0;
        int           valueCount        = 0;
        for (int i=0; i<allModelArray.count; i++) {
            bpSubModel *heartSubModel = [allModelArray objectAtIndex:i];
            if (heartSubModel.count==k) {
                valueCount++;
                totalValue += heartSubModel.DBPValue;
            }
            if(i==allModelArray.count-1){
                if (totalValue &&valueCount) {
                    aveValue = totalValue/valueCount;
                }
                [dbpArray replaceObjectAtIndex:k withObject:StrByInt(aveValue)];
            }
        }
    }
    
    NSMutableArray *bpArray48 = [NSMutableArray array];
    for (int i = 0; i <sbpArray.count; i ++) {
        NSString *sbp = [sbpArray objectAtIndex:i];
        NSString *dbp = [dbpArray objectAtIndex:i];
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:sbp forKey:@"sbp"];
        [dic setObject:dbp forKey:@"dbp"];
        [bpArray48 addObject:dic];
    }
    
    return bpArray48;
}

- (void)loadDataWithModel:(FriendModel *)model
{
    NSArray *oxArray = [self getOXArray:model];
    NSArray *bpArray = [self getBpArray:model];
    
    //血压
    [self.lineChart setXMarkTitlesAndValues:oxArray titleKey:@"Xvalue" valueKey:@"value" withOtherArray:bpArray withColor:UIColorHEX(0xf9269b)]; // X轴刻度标签及相应的值
    [self.lineChart mapping];
    [self.lineChart reloadDatas];
}

@end
